package thread

import (
	"time"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/sdk"

	"ssdevice/common/constant"
	"ssdevice/common/dto"
	"ssdevice/common/enums"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
)

type DevHisDataThread struct {
}

func (DevHisDataThread) Run(threadName string) {
	logger.Infof("启动线程 - %s.", threadName)
	go func() {
		produceT := time.NewTicker(5 * time.Millisecond)
		consumeT := time.NewTicker(3 * time.Second)
		defer produceT.Stop()
		defer consumeT.Stop()
		dataList := make([]interface{}, 0)
		for {
			select {
			case <-produceT.C:
				// 不停地写到dataList
				s := constant.HisDataQueue.Dequeue()
				if s != nil {
					dataList = append(dataList, s)
				}
			case <-consumeT.C:
				if len(dataList) > 0 {
					// 批量处理数据
					dealDevHistoryData(dataList)
					// 清空(减少扩容)
					dataList = dataList[0:0]
				}
			}
		}
	}()
}

func dealDevHistoryData(dataList []interface{}) {
	db := sdk.Runtime.GetDbByKey("db")
	if db == nil {
		return
	}
	sysHisSensorModel := &models.SysHistorySensor{}
	sysHisSensorModel.Orm = db
	sysHisSystemModel := &models.SysHistorySystem{}
	sysHisSystemModel.Orm = db
	insertSensorList := make([]models.SysHistorySensor, 0)
	insertSystemList := make([]models.SysHistorySystem, 0)
	for _, v := range dataList {
		cacheData := utils.JsonStrToMap(v.(string))
		sn := cacheData["sn"].(string)
		updateTime, _ := utils.FormatStrTime(cacheData["updateTime"].(string))
		dataMap := cacheData["data"].(map[string]interface{})
		msgType := cacheData["msgType"].(float64)
		for k, v := range dataMap {
			if msgType == float64(enums.SensorMsg) {
				insertSensorList = append(insertSensorList, models.SysHistorySensor{
					DevSn:      sn,
					Key:        k,
					Value:      utils.InterfaceToStr(v),
					UpdateTime: dto.LocalTime(updateTime),
				})
			} else if msgType == float64(enums.SystemMsg) {
				insertSystemList = append(insertSystemList, models.SysHistorySystem{
					DevSn:      sn,
					Key:        k,
					Value:      utils.InterfaceToStr(v),
					UpdateTime: dto.LocalTime(updateTime),
				})
			}
		}
	}

	if len(insertSensorList) > 0 {
		logger.Info("sensor历史记录入库.")
		if err := sysHisSensorModel.Add(&insertSensorList); err != nil {
			logger.Error(err)
		}
	}
	if len(insertSystemList) > 0 {
		logger.Info("system历史记录入库.")
		if err := sysHisSystemModel.Add(&insertSystemList); err != nil {
			logger.Error(err)
		}
	}
}
